<template>
  <div id="add_space_page">
    <h2 style="margin-bottom: 16px">{{ !!route.query.id ? '修改' : '新增' }}{{SPACE_TYPE_MAP[spaceType]}}</h2>
    <a-form
      layout="vertical"
      :model="formDate"
      name="basic"
      autocomplete="off"
      @finish="handleSubmit"
    >
      <a-form-item label="空间名称" name="spaceName">
        <a-input v-model:value="formDate.spaceName" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item v-if="loginUserStore.loginUser?.userRole == 'admin'" label="空间级别" name="tags">
        <a-select
          v-model:value="formDate.spaceLevel"
          style="width: 100%"
          placeholder="请输入空间级别"
          :options="SPACE_LEVEL_OPTIONS"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item v-if="!!route.query.id" label="空间大小" name="">
        <a-input v-model:value="formDate.maxSize" placeholder="请输入空间大小(MB)" /> </a-form-item
      ><a-form-item v-if="!!route.query.id" label="空间条数" name="spaceName">
        <a-input v-model:value="formDate.maxCount" placeholder="请输入空间条数" />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" style="width: 100%" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
    <a-card title="空间级别介绍">
      <a-typography-paragraph>
        * 目前仅支持开通普通版，如需要升级，请联系
        <a href="#" target="_blank">管理员</a>
      </a-typography-paragraph>
      <a-typography-paragraph v-for="spaceLevel in spaceLevelList">
        {{ spaceLevel.text }}：大小:{{ formatSize(spaceLevel.maxSize) }}，数量:{{
          spaceLevel.maxCount
        }}
      </a-typography-paragraph>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'

import { SPACE_LEVEL_ENUM, SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS } from '@/constants/spaceConstant.ts'
import {
  addSpaceUsingPost, editSpaceUsingPost,
  getSpaceVoByIdUsingGet,
  listSpaceLevelUsingGet,
  updateSpaceUsingPost
} from '@/request/api/spaceController.ts'
import { formatSize } from '@/utils'
import { useLoginUserStore } from '@/stores/useUserLoginStore.ts'
import { SPACE_TYPE_ENUM, SPACE_TYPE_MAP } from '@/constants/spaceUserConstant.ts'

const router = useRouter()
const route = useRoute()
const loginUserStore = useLoginUserStore()
const loading = ref(false)
const spaceLevelList = ref<API.SpaceLevelVO[]>([])
const oldSpace = ref<API.SpaceVO>()
// 表单信息
const formDate = reactive<API.SpaceAddRequest | API.SpaceUpdateRequest>({
  spaceName: '',
  spaceLevel: SPACE_LEVEL_ENUM.COMMON,
})

// 提交表单
const handleSubmit = async (value: API.PictureEditRequest) => {
  const spaceId = oldSpace.value?.id
  loading.value = true
  let result
  if (spaceId) {
    // 更新
    //判断是否是管理员
    if (loginUserStore.loginUser?.userRole == 'admin') {
      result = await updateSpaceUsingPost({
        id: spaceId,
        ...(formDate as API.SpaceUpdateRequest),
      })
    } else {
      // 不是管理员
      result=editSpaceUsingPost({
        id: spaceId,
        spaceName:  formDate.spaceName,
      })
    }
  } else {
    // 新增
    result = await addSpaceUsingPost({
      ...(formDate as API.SpaceAddRequest),
      spaceType: spaceType.value,
    })
  }
  const { data: res } = result
  if (res.code === 0 && res.data) {
    // 提交成功
    message.success('操作成功')
    // 跳转到空间详情
    router.push({
      path: `/space/${spaceId ?? res.data}`,
    })
  } else {
    // 提交失败
    message.error('操作失败' + res.message)
  }
  loading.value = false
}
// 获取空间级别
const fetchSpaceLevelList = async () => {
  const { data: res } = await listSpaceLevelUsingGet()
  if (res.code === 0 && res.data) {
    spaceLevelList.value = res.data
  } else {
    message.error('获取空间级别失败' + res.message)
  }
}
// 获取老数据
const getOldSpace = async () => {
  const id = route.query?.id
  if (id) {
    const { data: res } = await getSpaceVoByIdUsingGet({ id: id })
    if (res.code === 0 && res.data) {
      oldSpace.value = res.data
      formDate.spaceName = res.data.spaceName
      formDate.spaceLevel = res.data.spaceLevel
      formDate.maxSize = res.data.maxSize
      formDate.maxCount = res.data.maxCount
    }
  }
}

// 控制是是创建私有空间还是团队空间
const spaceType=computed(()=> {
  // 0或者不传为私有空间，1为团队空间
  if (route.query?.type) {
    return SPACE_TYPE_ENUM.TEAM
  }
  return SPACE_TYPE_ENUM.PRIVATE
})

onMounted(() => {
  fetchSpaceLevelList()
  getOldSpace()
})
</script>
<style lang="less" scoped>
#add_space_page {
  max-width: 720px;
  margin: 0 auto;
}
</style>
